<script setup lang="ts">
  import { Role } from '@/views/busic/role/types'
  import { PropType, ref, watch } from 'vue'
  import {
    useGetPermissionsById,
    useGetAllMenuPermission,
    useGetPermissionRender,
  } from './services'

  const { permissionRender, setPermissionRender } = useGetPermissionRender()
  const { permissions, getPermissionsLoading, getPermissions } = useGetPermissionsById()
  const { allMenuPermission, getAllMenuPermissionLoading, getAllMenuPermission } =
    useGetAllMenuPermission()

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: () => false,
    },
    role: {
      type: Object as PropType<Role>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
  }>()

  const visible = ref(false)

  const onClose = () => {
    visible.value = false
    emits('update:modelValue', false)
  }

  watch(props, (value) => {
    visible.value = value.modelValue
    if (value.modelValue) {
      getPermissions(props.role.id)
      getAllMenuPermission().then(() => {
        setPermissionRender(allMenuPermission.value)
      })
    }
  })
</script>

<template>
  <h-dialog
    v-model="visible"
    @close="onClose"
    :title="`分配【${props.role.name}】权限`"
    :loading="getPermissionsLoading || getAllMenuPermissionLoading"
  >
    <div class="permissions_container">
      <div
        class="permission"
        v-for="(permission, permissionIndex) in allMenuPermission"
        :key="permissionIndex"
        >{{ permission.name }}</div
      >
    </div>
    <template #footer>
      <HButton is-modal type="primary" v-if="!props.role.admin">保存</HButton>
      <HButton is-modal @click="onClose">取消</HButton>
    </template>
  </h-dialog>
</template>

<style scoped lang="scss"></style>
